#include "vbrid.h"
#include "qrcutil.h"

#include <QWebEngineView>
#include <httpclient.h>

VBrid::VBrid() {}

QString VBrid::name()
{
    return "鳥哥私房菜 - Linux 基礎學習篇訓練教材";
}

QString VBrid::prefix()
{
    return "https://linux.vbird.org/linux_basic_train/rockylinux9/";
}

bool VBrid::autoLoad()
{
    return true;
}

QStringList VBrid::searching(const QString &text)
{
    QStringList list;
    foreach (auto line , QR("://vbrid/rockylinux9.txt").split("\n", Qt::SkipEmptyParts)) {
        auto href = line.mid(line.indexOf("\"") + 1);
        href = href.mid(0, href.indexOf("\""));

        auto title = line.mid(line.indexOf(">")+1);
        title = title.mid(0, title.indexOf("<"));

        list << title;
    }
    return list;
}

Wiki::ContentMode VBrid::contentMode()
{
    return NoContent;
}

void VBrid::content(const QString &text, QWebEngineView *webview)
{
    foreach (auto line , QR("://vbrid/rockylinux9.txt").split("\n", Qt::SkipEmptyParts)) {
        auto href = line.mid(line.indexOf("\"") + 1);
        href = href.mid(0, href.indexOf("\""));

        auto title = line.mid(line.indexOf(">")+1);
        title = title.mid(0, title.indexOf("<"));

        if (title == text) {
            QString content = HttpClient::instance().get(prefix() + href).content();
            int slide_body_start = content.indexOf("<body>") + 6;
            int start = content.indexOf("<!-- 開始正式內文 -->");
            // content.indexOf("<!-- 本文的連結區部分 -->");
            int end = content.indexOf("<!-- end of sub content -->");
            int slide_body_end = content.indexOf("</body>");
            content = content.mid(0,slide_body_start) + content.mid(start, end) + "</div>" + content.mid(slide_body_end);
            if (webview) {
                qDebug() << prefix() + href.mid(0, href.indexOf(".php"));
                webview->setHtml(content.toUtf8(), prefix() + href.mid(0, href.indexOf(".php")));
            }
        }
    }
}
